#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <sys/select.h>
#include "log.hpp"
#include "Socket.hpp"

using namespace LogModule;
using namespace SocketModule;

#define NUM sizeof(fd_set)*8
const int gdefaultfd = -1;

class SelectServer
{
public:
    SelectServer(uint16_t port)
    :_port(port)
    ,_listen_socket(std::make_unique<TcpSocket>())
    ,_is_running(false)
    {}
    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        for(int i = 0;i<NUM;++i)
            _fd_array[i] = gdefaultfd;
        _fd_array[0] = _listen_socket->Fd();
    }
    void loop()
    {
        fd_set rfds;//读文件描述符集
        _is_running = true;
        while(_is_running)
        {
            //清空
            FD_ZERO(&rfds);
            int maxfd = gdefaultfd;
            //找出最大文件描述符
            for(int i = 0;i<NUM;++i)
            {
                if(_fd_array[i] == gdefaultfd)
                    continue;
                if(maxfd < _fd_array[i])
                    maxfd =  _fd_array[i];
                //更新读文件描述符表
                FD_SET(_fd_array[i],&rfds);
            }

            //std::cout<<"maxfd:"<<maxfd<<std::endl;
            timeval timeout = {10,0};//没有事件就绪时最多等十秒
            //select检查就绪事件
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout); 
            switch (n)
            {
            case 0:
                std::cout<<"time out..."<<std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                //事件就绪
                std::cout<<"事件就绪,timeout: "<<timeout.tv_sec<<":"<<timeout.tv_usec<<std::endl;
                Dispatcher(rfds);
                break;
            }
        }
    }
    //分发任务
    void Dispatcher(fd_set& rfds)
    {
        for(int i = 0;i<NUM;++i)
        {
            if(_fd_array[i] == gdefaultfd)
                continue;
            if(_fd_array[i] == _listen_socket->Fd())
            {
                //此时rfds中就绪的文件描述符已经被设置
                if(FD_ISSET(_fd_array[i],&rfds))
                    Accepter();
            }
            else
            {
                if(FD_ISSET(_fd_array[i],&rfds))
                    Recver(i);
            }
        }
        
    }
    //accept新连接
    void Accepter()
    {
        InetAddr client;
        SockPtr sockp = _listen_socket->Accept(&client);
        //搜索表中空闲位置
        int pos = -1;
        for(int i = 0;i<NUM;++i)
        {
            if(_fd_array[i] == gdefaultfd)
            {
                pos = i;
                break;
            }
        }
        if(pos == -1)
        {
            std::cout<<"服务器繁忙..."<<std::endl;
            sockp->Close();
        }
        else
        {
            //std::cout<<"pos:"<<pos<<std::endl;
            _fd_array[pos] = sockp->Fd();
            std::cout<<"新连接建立,ip:"<<client.Ip()<<" fd:"<<_fd_array[pos]<<std::endl; 
        }
    }
    void Recver(int who)
    {
        char buffer[1024] = {0};
        int n = recv(_fd_array[who],buffer,sizeof(buffer)-1,0);//因为文件描述符就绪，所以不会阻塞
        if(n>0)
        {
            std::cout<<"收到消息"<<buffer<<std::endl;
            //读到内容，回传给客户端
            std::string echo("server echo:");
            echo += buffer;
            send(_fd_array[who],echo.c_str(),echo.size(),0);
        }
        else if(n == 0)
        {
            std::cout<<"client quit,sockfd:"<<_fd_array[who]<<std::endl;
            close(_fd_array[who]);
            //删除对应的表中内容
            _fd_array[who] = gdefaultfd;
        }
        else
        {
            std::cout<<"recv error,disconnect:"<<_fd_array[who]<<std::endl;
            close(_fd_array[who]);
            _fd_array[who] = gdefaultfd;
        }
    }
private:
    uint16_t _port;//端口号
    std::unique_ptr<Socket> _listen_socket;//监听套接字
    bool _is_running;
    int _fd_array[NUM];//select用辅助数组
};
